<template>
  <div class="page-container">
    <Navbar />
    <main class="main-content">
      <div class="header-section">
        <h1 class="page-title">我的餐厅</h1>
        <button 
          class="primary-btn create-btn"
          @click="showCreateRestaurantDialog"
        >
          <span class="btn-icon">+</span> 创建新餐厅
        </button>
      </div>

      <!-- 餐厅列表 -->
      <div class="restaurant-list">
        <div v-if="myRestaurants.length === 0" class="empty-state">
          <!-- <img src="@/assets/empty-restaurant.svg" alt="空状态" class="empty-img"> -->
          <p>您还没有创建任何餐厅</p>
        </div>

        <table v-else class="styled-table">
          <thead>
            <tr>
              <th>ID</th>
          <th>餐厅名称</th>
          <th>用户ID</th>
          <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="restaurant in myRestaurants" :key="restaurant.id">
          <td class="monospace">{{ restaurant.id }}</td>
          <td>{{ restaurant.name }}</td>
          <td class="monospace">{{ restaurant.userId }}</td>
          <td>
            <button 
              class="action-btn manage-btn"
              @click="manageRestaurant(restaurant.id)"
            >
              管理
            </button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- 创建餐厅模态框 -->
      <div v-if="createRestaurantDialogVisible" class="modal-overlay">
        <div class="modal-container">
          <div class="modal-header">
            <h2>创建新餐厅</h2>
            <button class="close-btn" @click="createRestaurantDialogVisible = false">
              &times;
            </button>
          </div>
          
          <form @submit.prevent="handleCreateRestaurant" class="restaurant-form">
            <div class="form-group">
              <label for="name">餐厅名称</label>
              <input
                id="name"
                v-model="restaurantForm.name"
                type="text"
                required
                placeholder="请输入餐厅名称"
                class="form-input"
              >
            </div>
            
            <div class="form-group">
              <label for="address">餐厅地址</label>
              <input
                id="address"
                v-model="restaurantForm.address"
                type="text"
                required
                placeholder="请输入详细地址"
                class="form-input"
              >
            </div>

            <div class="form-actions">
              <button type="button" class="cancel-btn" @click="createRestaurantDialogVisible = false">
                取消
              </button>
              <button type="submit" class="submit-btn">
                创建餐厅
              </button>
            </div>
          </form>
        </div>
      </div>
    </main>
  </div>
</template>

<script setup>
import Navbar from '../Common/Navbar.vue'
import { ref, reactive, onMounted } from 'vue'
import { getRestaurants, createRestaurant } from '@/api'
import { useRouter } from 'vue-router'
const loading = ref(false)
const router = useRouter()
const myRestaurants = ref([])
const createRestaurantDialogVisible = ref(false)
const restaurantForm = reactive({ name: '', address: '' })
const manageRestaurant = (id) => {
  router.push({
    name: 'RestaurantDetail', // 必须使用命名路由
    params: {
      restaurantId: id // 保持数值类型
    },
    query: {
      name: myRestaurants.value.find(r => r.id === id)?.name
    }
  })
}
// 获取用户餐厅列表
const fetchRestaurants = async () => {
  try {
    loading.value = true
    const res = await getRestaurants()
    console.log('获取餐厅列表:', res)
    
    // 调试输出
    console.groupCollapsed('[API Response]')
    console.log('原始数据:', res)
    console.table(res.data) // 假设返回的是分页对象
    console.groupEnd()

    // 类型转换处理
    const userId = parseInt(localStorage.getItem('userId'))
    
    // 处理不同响应结构
    const rawData = Array.isArray(res) ? res : 
                   res.data ? res.data : 
                   res.items ? res.items : []
    console.log('处理后的数据:', rawData)
    myRestaurants.value = rawData
      // .filter(r => parseInt(r.userId) === userId)
      // .map(item => ({
      //   ...item,
      //   // 格式化显示
      //   id: `#${item.id.toString().padStart(4, '0')}`
      // }))
    console.log('过滤后的餐厅列表:', myRestaurants.value)
  } catch (error) {
    console.error('获取失败:', error)
    showMessage(`错误: ${error.message}`, 'error')
  } finally {
    loading.value = false
  }
}

const showCreateRestaurantDialog = () => {
  // 重置表单
  restaurantForm.name = ''
  restaurantForm.address = ''
  // 显示模态框
  createRestaurantDialogVisible.value = true
}
// 创建餐厅处理
const handleCreateRestaurant = async () => {
  try {
    const newRestaurant = {
      ...restaurantForm,
      userId: parseInt(localStorage.getItem('userId'))
    }
    
    const res = await createRestaurant(newRestaurant)
    console.log('创建结果:', res)

    // 修改成功判断逻辑
    if (res.id) {
      showMessage('创建成功', 'success')
      await fetchRestaurants()
      createRestaurantDialogVisible.value = false
      Object.assign(restaurantForm, { name: '', address: '' })
    }
  } catch (error) {
    showMessage(`创建失败: ${error.message}`, 'error')
  }
}

// 显示提示消息
const showMessage = (text, type) => {
  const msg = document.createElement('div')
  msg.className = `alert-message ${type}`
  msg.textContent = text
  document.body.appendChild(msg)
  setTimeout(() => msg.remove(), 3000)
}

onMounted(() => {
  if (!localStorage.getItem('token')) {
    router.push('/login')
  }
  fetchRestaurants()
})
</script>

<style scoped lang="scss">
.page-container {
  min-height: 100vh;
  background: #f5f7fa;
}

.main-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
}

.page-title {
  font-size: 2rem;
  color: #2d3748;
  margin: 0;
}

.create-btn {
  background: #4f46e5;
  color: white;
  padding: 0.75rem 1.5rem;
  border-radius: 8px;
  font-weight: 500;
  transition: transform 0.2s;

  &:hover {
    transform: translateY(-2px);
    background: #4338ca;
  }

  .btn-icon {
    margin-right: 0.5rem;
  }
}

.styled-table {
  width: 100%;
  border-collapse: collapse;
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);

  th, td {
    padding: 1rem;
    text-align: left;
  }

  th {
    background: #4f46e5;
    color: white;
    font-weight: 600;
  }

  tr:nth-child(even) {
    background: #f8fafc;
  }

  tr:hover {
    background: #f1f5f9;
  }
}

.action-btn {
  padding: 0.5rem 1rem;
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.2s;
}

.manage-btn {
  background: #4f46e5;
  color: white;

  &:hover {
    background: #4338ca;
  }
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-container {
  background: white;
  border-radius: 16px;
  width: 90%;
  max-width: 500px;
  padding: 2rem;
  box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;

  h2 {
    margin: 0;
    font-size: 1.5rem;
    color: #1e293b;
  }
}

.close-btn {
  background: none;
  border: none;
  font-size: 1.5rem;
  color: #64748b;
  cursor: pointer;
  padding: 0.5rem;

  &:hover {
    color: #475569;
  }
}

.restaurant-form {
  .form-group {
    margin-bottom: 1.5rem;

    label {
      display: block;
      margin-bottom: 0.5rem;
      color: #374151;
      font-weight: 500;
    }
  }

  .form-input {
    width: 100%;
    padding: 0.75rem;
    border: 2px solid #e2e8f0;
    border-radius: 8px;
    font-size: 1rem;
    transition: border-color 0.2s;

    &:focus {
      outline: none;
      border-color: #4f46e5;
      box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
    }
  }
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
  margin-top: 2rem;
}

.submit-btn {
  @extend .create-btn;
  padding: 0.75rem 1.5rem;
}

.cancel-btn {
  background: #f1f5f9;
  color: #64748b;
  padding: 0.75rem 1.5rem;
  border-radius: 8px;
  font-weight: 500;

  &:hover {
    background: #e2e8f0;
  }
}

.empty-state {
  text-align: center;
  padding: 4rem 0;
  background: white;
  border-radius: 12px;

  .empty-img {
    width: 200px;
    margin-bottom: 1rem;
    opacity: 0.8;
  }

  p {
    color: #64748b;
    font-size: 1.125rem;
  }
}

.alert-message {
  position: fixed;
  top: 1rem;
  right: 1rem;
  padding: 1rem 1.5rem;
  border-radius: 8px;
  color: white;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);

  &.success {
    background: #10b981;
  }

  &.error {
    background: #ef4444;
  }
}

@media (max-width: 768px) {
  .header-section {
    flex-direction: column;
    align-items: flex-start;
    gap: 1rem;
  }

  .styled-table {
    th, td {
      padding: 0.75rem;
    }
  }
}
</style>